import React, { useState } from 'react';
import { 
  Table, 
  Button, 
  Space, 
  Tag, 
  Modal, 
  Form, 
  Input, 
  Select, 
  Typography,
  Checkbox,
  Card
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  EyeOutlined,
  SafetyCertificateOutlined
} from '@ant-design/icons';
import { useThemeStore } from '../../../stores/themeStore';
import { getTheme } from '../../../theme/config';
import { motion } from 'framer-motion';
import { notification } from '../../../components/common'; // 导入自定义通知组件

const { Title, Text } = Typography;
const { Option } = Select;

interface Role {
  id: number;
  name: string;
  description: string;
  permissions: string[];
  status: 'active' | 'inactive';
  createdAt: string;
  updatedAt: string;
}

const RolesManagement: React.FC = () => {
  const { mode } = useThemeStore();
  const theme = getTheme(mode);
  const [roles, setRoles] = useState<Role[]>([
    {
      id: 1,
      name: '超级管理员',
      description: '拥有系统所有权限',
      permissions: ['用户管理', '角色管理', '权限管理', '系统配置'],
      status: 'active',
      createdAt: '2023-01-15',
      updatedAt: '2023-10-20'
    },
    {
      id: 2,
      name: '管理员',
      description: '拥有大部分管理权限',
      permissions: ['用户管理', '角色管理'],
      status: 'active',
      createdAt: '2023-03-22',
      updatedAt: '2023-10-19'
    },
    {
      id: 3,
      name: '普通用户',
      description: '基础用户权限',
      permissions: ['查看数据'],
      status: 'active',
      createdAt: '2023-05-10',
      updatedAt: '2023-10-10'
    }
  ]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingRole, setEditingRole] = useState<Role | null>(null);
  const [form] = Form.useForm();

  // 权限选项
  const permissionOptions = [
    '用户管理',
    '角色管理',
    '权限管理',
    '系统配置',
    '数据管理',
    '日志查看',
    '报表查看',
    'API访问'
  ];

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80
    },
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description'
    },
    {
      title: '权限数量',
      dataIndex: 'permissions',
      key: 'permissions',
      render: (permissions: string[]) => (
        <motion.div
          whileHover={{ scale: 1.1 }}
          whileTap={{ scale: 0.9 }}
        >
          <Tag color="blue">{permissions.length}</Tag>
        </motion.div>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: 'active' | 'inactive') => (
        <motion.div
          whileHover={{ scale: 1.1 }}
          whileTap={{ scale: 0.9 }}
        >
          <Tag color={status === 'active' ? 'green' : 'red'}>
            {status === 'active' ? '激活' : '停用'}
          </Tag>
        </motion.div>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt'
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt'
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Role) => (
        <Space size="middle">
          <motion.div whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
            <Button 
              type="primary" 
              icon={<EyeOutlined />} 
              size="small"
              onClick={() => handleViewRole(record)}
              style={{ 
                background: theme.glowColor,
                borderColor: theme.glowColor
              }}
            >
              查看
            </Button>
          </motion.div>
          <motion.div whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
            <Button 
              icon={<EditOutlined />} 
              size="small"
              onClick={() => handleEditRole(record)}
            >
              编辑
            </Button>
          </motion.div>
          <motion.div whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
            <Button 
              icon={<DeleteOutlined />} 
              size="small"
              danger
              onClick={() => handleDeleteRole(record)}
            >
              删除
            </Button>
          </motion.div>
        </Space>
      )
    }
  ];

  const handleViewRole = (role: Role) => {
    Modal.info({
      title: '角色详情',
      content: (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.3 }}
        >
          <Card style={{ 
            background: theme.cardBackground,
            borderColor: theme.cardBorder
          }}>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.1 }}
            >
              <p><Text strong>角色名称:</Text> {role.name}</p>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.2 }}
            >
              <p><Text strong>描述:</Text> {role.description}</p>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.3 }}
            >
              <p><Text strong>状态:</Text> {role.status === 'active' ? '激活' : '停用'}</p>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.4 }}
            >
              <p><Text strong>权限:</Text></p>
              <div>
                {role.permissions.map((perm, index) => (
                  <motion.div
                    key={index}
                    style={{ display: 'inline-block' }}
                    initial={{ opacity: 0, scale: 0.8 }}
                    animate={{ opacity: 1, scale: 1 }}
                    transition={{ duration: 0.3, delay: 0.5 + index * 0.1 }}
                  >
                    <Tag color="blue" style={{ margin: '4px' }}>{perm}</Tag>
                  </motion.div>
                ))}
              </div>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.6 }}
            >
              <p><Text strong>创建时间:</Text> {role.createdAt}</p>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.7 }}
            >
              <p><Text strong>更新时间:</Text> {role.updatedAt}</p>
            </motion.div>
          </Card>
        </motion.div>
      ),
      okText: '确定',
      icon: <SafetyCertificateOutlined style={{ color: theme.glowColor }} />
    });
  };

  const handleEditRole = (role: Role) => {
    setEditingRole(role);
    form.setFieldsValue({
      ...role,
      permissions: role.permissions
    });
    setIsModalVisible(true);
  };

  const handleDeleteRole = (role: Role) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除角色 "${role.name}" 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        setRoles(roles.filter(r => r.id !== role.id));
        // 使用自定义通知组件替换 message.success
        notification.success({
          title: '角色删除',
          message: '角色已成功删除'
        });
      },
      icon: <DeleteOutlined style={{ color: '#ff4d4f' }} />
    });
  };

  const handleAddRole = () => {
    setEditingRole(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleModalOk = () => {
    form.validateFields().then(values => {
      if (editingRole) {
        // 更新角色
        setRoles(roles.map(role => 
          role.id === editingRole.id ? { ...role, ...values, updatedAt: new Date().toISOString().split('T')[0] } : role
        ));
        // 使用自定义通知组件替换 message.success
        notification.success({
          title: '角色更新',
          message: '角色已成功更新'
        });
      } else {
        // 添加角色
        const newRole = {
          ...values,
          id: roles.length + 1,
          createdAt: new Date().toISOString().split('T')[0],
          updatedAt: new Date().toISOString().split('T')[0]
        };
        setRoles([...roles, newRole]);
        // 使用自定义通知组件替换 message.success
        notification.success({
          title: '角色添加',
          message: '角色已成功添加'
        });
      }
      setIsModalVisible(false);
    });
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
  };

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.3 }}
    >
      <div style={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center', 
        marginBottom: 24 
      }}>
        <motion.div
          initial={{ opacity: 0, x: -20 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ duration: 0.3 }}
        >
          <Title level={3} style={{ color: theme.textPrimary, margin: 0 }}>
            角色管理
          </Title>
        </motion.div>
        <motion.div
          initial={{ opacity: 0, x: 20 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ duration: 0.3 }}
          whileHover={{ scale: 1.05 }}
          whileTap={{ scale: 0.95 }}
        >
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={handleAddRole}
            style={{ 
              background: theme.glowColor,
              borderColor: theme.glowColor,
              boxShadow: theme.cardShadow
            }}
          >
            添加角色
          </Button>
        </motion.div>
      </div>
      
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.3, delay: 0.1 }}
      >
        <Table
          dataSource={roles}
          columns={columns}
          rowKey="id"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true
          }}
          style={{
            background: theme.cardBackground,
            borderRadius: '12px',
            overflow: 'hidden',
            boxShadow: theme.cardShadow
          }}
          scroll={{ x: true }}
        />
      </motion.div>
      
      <Modal
        title={editingRole ? "编辑角色" : "添加角色"}
        visible={isModalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        okText="确定"
        cancelText="取消"
        width={600}
        style={{ 
          borderRadius: '12px'
        }}
      >
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.3 }}
        >
          <Form form={form} layout="vertical">
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.1 }}
            >
              <Form.Item
                name="name"
                label="角色名称"
                rules={[{ required: true, message: '请输入角色名称' }]}
              >
                <Input 
                  placeholder="请输入角色名称"
                  style={{ 
                    borderRadius: '8px'
                  }}
                />
              </Form.Item>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.2 }}
            >
              <Form.Item
                name="description"
                label="描述"
                rules={[{ required: true, message: '请输入角色描述' }]}
              >
                <Input.TextArea 
                  rows={3} 
                  placeholder="请输入角色描述"
                  style={{ 
                    borderRadius: '8px'
                  }}
                />
              </Form.Item>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.3 }}
            >
              <Form.Item
                name="permissions"
                label="权限"
                rules={[{ required: true, message: '请选择权限' }]}
              >
                <Checkbox.Group style={{ width: '100%' }}>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
                    {permissionOptions.map((option, index) => (
                      <motion.div
                        key={option}
                        initial={{ opacity: 0, x: -10 }}
                        animate={{ opacity: 1, x: 0 }}
                        transition={{ duration: 0.3, delay: 0.4 + index * 0.05 }}
                      >
                        <Checkbox value={option}>
                          {option}
                        </Checkbox>
                      </motion.div>
                    ))}
                  </div>
                </Checkbox.Group>
              </Form.Item>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.5 }}
            >
              <Form.Item
                name="status"
                label="状态"
                initialValue="active"
              >
                <Select style={{ borderRadius: '8px' }}>
                  <Option value="active">激活</Option>
                  <Option value="inactive">停用</Option>
                </Select>
              </Form.Item>
            </motion.div>
          </Form>
        </motion.div>
      </Modal>
    </motion.div>
  );
};

export default RolesManagement;